package ncs.teacher.action;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;

import javax.servlet.ServletContext;

import ncs.common.database.ResourceDAO;
import ncs.common.model.Resource;
import ncs.common.model.SessionStore;
import ncs.common.util.Util;

import org.apache.struts2.util.ServletContextAware;

import com.opensymphony.xwork2.ActionSupport;

public class UploadResourceAction extends ActionSupport implements ServletContextAware{
	private static final long serialVersionUID = 1L;
	private InputStream inputStream;
	private ServletContext context;
	private File resource;
	private String resourceFileName;
	private String resourceContentType;
	public InputStream getInputStream() {
		return inputStream;
	}
	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}
	public ServletContext getContext() {
		return context;
	}
	public void setContext(ServletContext context) {
		this.context = context;
	}
	public File getResource() {
		return resource;
	}
	public void setResource(File resource) {
		this.resource = resource;
	}
	public String getResourceFileName() {
		return resourceFileName;
	}
	public void setResourceFileName(String resourceFileName) {
		this.resourceFileName = resourceFileName;
	}
	public String getResourceContentType() {
		return resourceContentType;
	}
	public void setResourceContentType(String resourceContentType) {
		this.resourceContentType = resourceContentType;
	}
	@Override
	public void setServletContext(ServletContext con) {
		context=con;
	}
	public String uploadResource() throws Exception{
		Resource r=new Resource();
		SessionStore store=Util.getSessionStore();
		r.setCourse_id(store.getCourse_id());
		r.setUploader(store.getUserName());
		r.setName(resourceFileName);
		r.setSize((int)resource.length());
		
		String path=String.format("%s/%d",context.getRealPath("/upload"),r.getCourse_id());
		File dir=new File(path);
		if(!dir.exists())
			dir.mkdirs();
		resourceFileName=Util.getUniqueName(path, resourceFileName);
		r.setLocalName(resourceFileName);
		resource.renameTo(new File(path+"/"+resourceFileName));
		
		ResourceDAO dao=new ResourceDAO();
		dao.addResource(r);
		String json="{'success':true}";
		inputStream=new ByteArrayInputStream(json.getBytes("UTF-8"));
		return SUCCESS;
	}
}
